<script setup lang="ts" name="InspectionReport">
import {ColorRed, IconConfig} from '@/api/config'
import {
  CheckReportItemGroup,
  getItemGroupRequired,
  getItemDetails,
  getItemGroup,
  ItemList,
  rejectCheckReport,
  saveCheckReport
} from '@/api/medicalExaminerDesk/beginPhysicalExamination/inspectionReport'
import {HeaderData} from '@/components/dTable/dTable'
import dTable from '@/components/dTable/dTable.vue'
import dIcon from '@/components/dIcon.vue'
import {NotLeadingAndTrailingSpaces} from '@/util/common'
import {ElMessage, FormRules} from 'element-plus/es'
import {onMounted, reactive, ref, computed, onBeforeUnmount, onDeactivated} from 'vue'
import useUser from '@/store/user'
import {getPrecisionResult} from '@/api/examinationManager/resultReview'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

//体检医生id
const dutyDoctorId = ref<string | undefined>()
// 体检医生姓名
const dutyDoctorName = ref<string | undefined>()

// 体检状态
const checkupStatus = ref<number | undefined>()

// 体检大类的体检医生姓名
const dutyDoctorName9 = computed(() => {
  return dutyDoctorName.value || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

//默认选中
const defualtSeleted = ref<CheckReportItemGroup | undefined>(undefined)

// 左侧列表
const tableRef = ref()

// 左侧项目组合表头
const inspectionReportTypeHeader = ref<Array<HeaderData>>([{prop: 'itemGroupName', label: '检验项目组合', columnType: 'text', align: 'left', 'min-width': '200'}])
// 左侧项目组合列表
const inspectionReportType = ref<Array<CheckReportItemGroup>>([])

const inspectionReportTypeLoading = ref<boolean>(false)

// 检验报告表头
const inspectionReportHeader = ref<Array<HeaderData>>([
  {prop: 'itemName', label: '项目名称', columnType: 'text', align: 'left', 'min-width': '200'},
  {prop: 'result', label: '结果', columnType: 'slot', align: 'left', 'min-width': '200'},
  {prop: 'unitName', label: '单位', columnType: 'text', align: 'left', 'min-width': '100'},
  {prop: 'tips', label: '提示', columnType: 'text', align: 'left', 'min-width': '150'},
  {prop: 'viewRange', label: '参考区间', columnType: 'text', align: 'left', 'min-width': '100'},
  {prop: 'reportTime', label: '检验日期', columnType: 'text', align: 'left', 'min-width': '100'},
  {prop: 'inspectDoctorName', label: '检验者', columnType: 'text', align: 'left', 'min-width': '100'}
])

// 表单实例
const formRef = ref()

// 控制是否现在校验提示
const showErrorTips = ref<boolean>(true)

// 错提示图标
const errorIcon: IconConfig = {
  icon: 'CircleCloseFilled',
  type: 'el',
  size: 16,
  color: ColorRed
}

// 项目组合是否必填
const fieldRequired = ref<boolean>(false)

const rules = computed<FormRules>(() => {
  return {
    result: [
      {required: fieldRequired.value, message: '请输入结果!', trigger: []},
      {
        message: '最多10个字符!',
        trigger: ['change', 'blur'],
        max: 10
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ]
  }
})
// 检验报告列表
const formData = reactive<{inspectionReportTable: Array<ItemList>}>({inspectionReportTable: []})

const inspectionReportLoading = ref<boolean>(false)

// 如果没有检验项目禁用编辑
const disEdit9 = computed(() => {
  return formData.inspectionReportTable.length === 0 || inspectionReportType.value.length === 0
})

// 体检状态
const checkupStatus9 = computed(() => {
  return checkupStatus.value
})

/**
 * @description: 获取项目组合的必填项
 * @param {*} itemGroupId
 * @return {*}
 */
const getRequiredFilds = (itemGroupId: string) => {
  getItemGroupRequired({itemGroupIds: itemGroupId}).then((res) => {
    fieldRequired.value = !!res.data?.data?.[0].isRequired
  })
}

/**
 * @description: 获取体检信息
 * @return {*}
 */
const getInitData = () => {
  inspectionReportTypeLoading.value = true
  props.checkupRegisterId &&
    getItemGroup({checkupRegisterId: props.checkupRegisterId, checkType: 2})
      .then((res) => {
        const {data} = res.data
        // 左侧项目组合数据
        inspectionReportType.value = data
        // 默认选择第一行显示右侧数据
        if (!inspectionReportType.value.length) {
          defualtSeleted.value = undefined
          formData.inspectionReportTable = []
        } else {
          // 初始化默认选中第一行
          !defualtSeleted.value && (defualtSeleted.value = inspectionReportType.value[0])
        }
        // 找到选中行的坐标
        const rowIndex = inspectionReportType.value?.findIndex((item) => {
          return item.itemGroupId === defualtSeleted.value?.itemGroupId
        })
        tableRef.value?.setSeleted(inspectionReportType.value[rowIndex]) // 选中上次的行
      })
      .catch((err) => {
        console.warn(err)
      })
      .finally(() => {
        inspectionReportTypeLoading.value = false
        showSaveLoading.value = false
      })
}

/**
 * @description: 保存
 * @return {*}
 */
const onSave9 = () => {
  showErrorTips.value = true
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        const baseParams = {
          checkupStatus: 2, //2已检
          checkupRegisterId: props.checkupRegisterId,
          checkType: 2 // 检验类型
        }
        const params: Array<Partial<ItemList & CheckReportItemGroup>> = []
        formData.inspectionReportTable?.forEach((el, index) => {
          el.result = getPrecisionResult(el.result, el.precision) ? getPrecisionResult(el.result, el.precision)?.toString() : null
          params.push({
            ...baseParams,
            dutyDoctorId: el.dutyDoctorId || user.userInfor?.id, // 体检医生id
            dutyDoctorName: el.dutyDoctorId !== user.userInfor?.id ? el.dutyDoctorName || user.userInfor?.userName : user.userInfor?.userName, // 体检医生
            reportTime: el.reportTime, // 结果时间
            itemGroupId: el.itemGroupId, // 项目组合id
            itemGroupCode: el.itemGroupCode, // 项目组合编码
            itemGroupName: el.itemGroupName, // 项目组合名称
            itemName: el.itemName, // 项目名称
            itemCode: el.itemCode, // 项目编码
            itemId: el.itemId, // 项目id
            id: el.id,
            result: el.result, // 结果
            sort: index // 用于排序
          })
        })
        saveCheckReport(params)
          .then(() => {
            getInitData()
            ElMessage.success(`${defualtSeleted.value?.itemGroupName}保存成功!`)
          })
          .catch((err) => {
            showSaveLoading.value = false
            console.warn(err)
          })
      } else {
        console.warn(fields)
      }
    })
}

/**
 * @description: 拒检
 * @return {*}
 */
const onRejectInspection9 = () => {
  showMessageBox('是否对该体检大类进行拒检操作？', {title: '拒检确认', mesageType: 'base'})
    .then(() => {
      showSaveLoading.value = true
      const baseParams = {
        checkupRegisterId: props.checkupRegisterId, // 体检登记表id
        dutyDoctorId: dutyDoctorId.value || user.userInfor?.id, // 体检医生id
        dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName, // 体检医生姓名
        checkupStatus: 1, // 1拒检
        checkType: 2 // 检验类型
      }
      const params: Array<ItemList> = []
      formData.inspectionReportTable?.forEach((el, index) => {
        params.push({
          ...baseParams,
          itemGroupId: el.itemGroupId, // 项目组合id
          itemGroupCode: el.itemGroupCode, // 项目组合编码
          itemGroupName: el.itemGroupName, // 项目组合名称
          itemName: el.itemName, // 项目名称
          itemId: el.itemId, // 项目id
          itemCode: el.itemCode, // 项目编码
          id: el.id,
          sort: index // 用于排序
        })
      })
      rejectCheckReport(params)
        .then(() => {
          ElMessage.success(`${defualtSeleted.value?.itemGroupName}拒检成功!`)
          getInitData()
        })
        .catch((error) => {
          showSaveLoading.value = false
          console.warn(error)
        })
    })
    .catch((error) => {
      console.warn(error)
    })
}

//行点击回调
const onRowClick = (row: CheckReportItemGroup) => {
  if (row) {
    defualtSeleted.value = row // 左侧列表当前选中行
    inspectionReportLoading.value = true
    const params = {
      checkupRegisterId: props.checkupRegisterId, // 体检登记表id
      checkType: 2, // 检验类型
      itemGroupId: row.itemGroupId //  项目组合id
    }
    getItemDetails(params)
      .then((res) => {
        const {data} = res.data
        formData.inspectionReportTable = data || []
      })
      .catch((err) => {
        console.warn(err)
        defualtSeleted.value = undefined
        formData.inspectionReportTable = []
      })
      .finally(() => {
        inspectionReportLoading.value = false
        // 获取当前行的体检医生
        formData.inspectionReportTable[0]?.dutyDoctorId && (dutyDoctorId.value = formData.inspectionReportTable[0]?.dutyDoctorId)
        formData.inspectionReportTable[0]?.dutyDoctorName && (dutyDoctorName.value = formData.inspectionReportTable[0]?.dutyDoctorName)
        checkupStatus.value = formData.inspectionReportTable[0]?.checkupStatus
        formRef.value?.clearValidate()
      })
    getRequiredFilds(row.itemGroupId)
  } else {
    defualtSeleted.value = undefined
    formData.inspectionReportTable = []
    checkupStatus.value = undefined
  }
}

onMounted(() => {
  getInitData()
})

onBeforeUnmount(() => {
  showErrorTips.value = false
})

onDeactivated(() => {
  showErrorTips.value = false
})
</script>
<template>
  <div class="d-common-flex-full d-check-up-desk-content">
    <d-table
      ref="tableRef"
      class="inspection-report-type"
      :table-data="inspectionReportType"
      :show-loading="inspectionReportTypeLoading"
      :table-header-data="inspectionReportTypeHeader"
      :default-seleted="defualtSeleted"
      @row-click="onRowClick"
    />
    <el-form ref="formRef" class="inspection-report-table" :rules="rules" :model="formData" :disabled="disEdit9 || disEdit">
      <d-table :table-data="formData.inspectionReportTable" :table-header-data="inspectionReportHeader" :show-loading="inspectionReportLoading" :highlight-current-row="false" :stripe="true">
        <template #result="scope">
          <el-form-item :prop="`inspectionReportTable.${scope.index}.result`" :rules="rules.result" :inline-message="true" class="d-common-width-full">
            <el-input v-model="scope.row.result" placeholder="请输入结果" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
      </d-table>
    </el-form>
  </div>
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName9" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit9 || disEdit" @click="onSave9()">
      保存
    </el-button>
    <el-button type="danger" :loading="showSaveLoading" :disabled="disEdit9 || (checkupStatus9 && checkupStatus9 === 1) || disEdit" plain @click="onRejectInspection9()">
      拒检
    </el-button>
  </div>
</template>
<style scoped lang="less">
.inspection-report-type {
  width: 260px;
  height: 72vh;
  :deep(.current-row) {
    .el-table__cell {
      background: transparent;
      .cell {
        background: var(--el-table-current-row-bg-color);
      }
    }
  }
  :deep(.el-table__cell) {
    border: none;
    .cell {
      width: 244px !important;
      height: 32px;
      margin: 0 auto;
      line-height: 32px;
      border-radius: 4px;
      cursor: pointer;
    }
  }
}
.inspection-report-table {
  flex: 1;
  margin-left: 12px;
}
</style>
